package com.tcxhb.job.admin.convert;

import com.tcxhb.job.dao.dataobject.JobInstanceDO;
import com.tcxhb.job.dao.dataobject.query.JobInstanceQuery;
import com.tcxhb.job.admin.model.request.query.JobInstanceQueryReq;
import com.tcxhb.job.admin.model.response.JobInstanceVO;
import com.tcxhb.job.common.constants.enums.ExecuteStatus;
import com.tcxhb.job.common.constants.enums.ScheduleStatus;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;

import java.util.Date;

@Mapper(componentModel = "spring")
public interface JobInstanceConvert {
    @Mappings({
            @Mapping(target = "scheduleTime", expression = "java(toDate(instance.getScheduleTime()))"),
            @Mapping(target = "status", expression = "java(toStatus(instance))"),
    })
    public JobInstanceVO do2VO(JobInstanceDO instance);


    public JobInstanceQuery toQuery(JobInstanceQueryReq req);


    default JobInstanceQuery defQuery(JobInstanceQueryReq req){
        JobInstanceQuery query = toQuery(req);
        //状态设置
        if(req.getStatus() == null){
            return query;
        }
        //运行中
        if(req.getStatus() == 15){
            query.setMinExeStatus(ExecuteStatus.INIT.getType());
            query.setMaxExeStatus(ExecuteStatus.RUNNING.getType());
        }
        //运行成功
        if(req.getStatus() == 18){
            query.setExecuteStatus(ExecuteStatus.SUCC.getType());
        }
        //运行失败
        if(req.getStatus() == 20){
            query.setExecuteStatus(ExecuteStatus.FAIL.getType());
        }
        return query;
    }


    default Integer toStatus(JobInstanceDO instance) {
        if (ExecuteStatus.INIT.eq(instance.getExecuteStatus())) {
            //已经提交成功了;并且是初始化状态
            if (ScheduleStatus.SUCC.eq(instance.getScheduleStatus())) {
                return ExecuteStatus.RUNNING.getType();
            }
            return instance.getScheduleStatus();
        }
        return instance.getExecuteStatus();
    }

    default Date toDate(Long timestamp) {
        if (timestamp == 0) {
            return null;
        }
        return new Date(timestamp);
    }
}
